import * as Cesium from 'cesium';

export class startAreaMeasure {
  constructor() {
    this.clearMeasurements();

    let positions = [];
    let polygon = this.viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.CallbackProperty(() => new Cesium.PolygonHierarchy(positions), false),
        material: new Cesium.ColorMaterialProperty(Cesium.Color.RED.withAlpha(0.5)),
      },
    });

    const handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    handler.setInputAction((movement) => {
      const ray = this.viewer.camera.getPickRay(movement.position);
      const cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
      if (cartesian) {
        positions.push(cartesian);
        if (positions.length >= 3) {
          const area = Cesium.PolygonGeometry.computeArea(
            new Cesium.PolygonHierarchy(positions)
          );
          console.log(`面积: ${area.toFixed(2)} 平方米`);
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 右键结束测量
    handler.setInputAction(() => {
      handler.destroy();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

    this.measureHandler = handler;
    this.measureEntities.push(polygon);
  }
  clearMeasurements() {
    // Remove all existing measurement entities
    if (this.measureEntities) {
      this.measureEntities.forEach(entity => {
        this.viewer.entities.remove(entity);
      });
      this.measureEntities = [];
    }

    // Remove existing event handler
    if (this.measureHandler && !this.measureHandler.isDestroyed()) {
      this.measureHandler.destroy();
      this.measureHandler = null;
    }
  }
}
